<template>
  <div>
    <el-form
      ref="registerForm"
      :model="registerForm"
      :rules="registerRule"
      label-position="left"
    >
      <!--用户名-->
      <el-form-item prop="username" label="用户名">
        <el-input
          v-model="registerForm.username"
        ></el-input>
      </el-form-item>
      <!--密码-->
      <el-form-item prop="password" label="密码">
        <el-input
          v-model="registerForm.password"
        ></el-input>
      </el-form-item>
      <!--注册按钮-->
      <el-button @click="register">
        注册
      </el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
      registerForm: {
        username: '',
        password: '123456'
      },
      registerRule: {
        // 用户名规则
        username: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入用户名'))
            } else if (value.length < 3) {
              callback(new Error('用户名不得少于3个字'))
            } else {
              callback()
            }
          }
        }],
        // 密码规则
        password: [{
          require: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入密码'))
            } else if (value.length < 6) {
              callback(new Error('用户名不得少于6个字符'))
            } else {
              callback()
            }
          }
        }]
      }
    }
  },
  methods: {
    register () {
      // 验证表单
      this.$refs.registerForm.validate(valid => {
        // 表单正确
        if (valid) {
          // 触发登录操作(action)
          this.$store.dispatch('user/register', this.registerForm).then(() => {
            this.$router.push({ path: '/login' })
            console.log('view/register:注册成功')
          }).catch(() => {})
        } else {
          alert('输入表单错误')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
